package club.gggd.security_jwt_demo.service.impl;

import club.gggd.security_jwt_demo.pojo.entity.SysUser;
import club.gggd.security_jwt_demo.pojo.module.BusinessException;
import club.gggd.security_jwt_demo.pojo.module.JwtUser;
import club.gggd.security_jwt_demo.pojo.module.ResultCode;
import club.gggd.security_jwt_demo.service.UserService;
import club.gggd.security_jwt_demo.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Description
 * @Author srx
 * @date 2023/12/10 15:44
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        // 获取用户信息
        UserService userService = (UserService) applicationContext.getBean("userServiceImpl");
        SysUser user = userService.getUserInfo(account);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_FOUND);
        }
        // 组装成userDetails
        JwtUser jwtUser = new JwtUser(
                user.getId(),
                user.getAccount(),
                user.getUserName(),
                user.getPassword(),
                userService.getAuthList(user.getId()),
                user.getEnabled() == 1 ? true : false
        );
        // 存入Redis
        String s = JSON.toJSONString(jwtUser);
        redisUtil.set("user:userDetail:" + user.getAccount(), s);
        return jwtUser;
    }
}
